import React, { useEffect, useState } from 'react'
import { Button, Modal, Form, Input, Image } from 'antd';
import axios from '../../aixos';
import Table from '../../components/Table/Table'
import Upload from '../../components/Upload/Upload';

export default function Category() {
  const [categoryList, setCategoryList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageIndex, setPageIndex] = useState(1)
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState(null)
  const [editRecordId, setEditRecordId] = useState(null)
  const [icon, setIcon] = useState('')

  const pageSize = 10
  useEffect(() => {
    axios.get('/category', {
      pageIndex,
      pageSize
    }).then(res => {
      setCategoryList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])
  const changePage = (index) => {
    setPageIndex(index)
  }
  const add = () => {
    setIcon('')
    setEditRecordId('')
    form.resetFields()
    setModalTitle('添加')
    setIsModalVisible(true)
  }

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const edit = (record) => {
    setModalTitle('编辑')
    setIcon('')
    form.resetFields()
    form.setFieldsValue({ ...record })
    setEditRecordId(record._id)
    setIsModalVisible(true)
  }
  const del = (id) => {
    axios.delete('/category', {
      id
    }).then(() => {
      setCategoryList(categoryList.filter(item => item._id !== id))
    })
  }

  const submit = async () => {
    console.log(form.getFieldsValue())
    const formData = await form.validateFields()
    formData.icon = icon
    console.log(formData)
    if (!editRecordId) {
      axios.post('/category', formData).then(res => {
        setCategoryList([res.data, ...categoryList])
        setIsModalVisible(false);
      })
    } else {
      axios.put('/category', {
        id: editRecordId,
        name: formData.name,
        icon: formData.icon
      }).then(() => {
        setCategoryList(categoryList.map(item => {
          if (item._id === editRecordId) return { ...item, ...formData }
          return item
        }))
        setIsModalVisible(false)
      })
    }
  };

  const [form] = Form.useForm();
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      render: text => <span>{text}</span>,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      render: icon => <Image width={50} height={50} src={icon}></Image>,
    },
    // {
    //   title: '操作',
    //   render: (_, record) => (
    //     <Space size="middle">
    //       <Button type='primary' onClick={() => edit(record)}>编辑</Button>
    //       <Button type='danger' onClick={() => del(record._id)}>删除</Button>
    //     </Space>
    //   ),
    // },
  ];
  return (
    <div>
      <Table rowKey='_id' columns={columns} dataSource={categoryList} pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 条数据`,
        onChange: changePage
      }}
        action={{
          edit: { callback: edit },
          delete: { callback: del }
        }}
      >
        <Button onClick={add}>添加分类</Button>
      </Table>
      <Modal title={modalTitle} cancelText='取消' okText='确认'
        visible={isModalVisible} onOk={submit} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="分类名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入分类名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="分类图标" name="icon" required rules={[
          {
            validator: () => {
              if (!icon) {
                return Promise.reject(new Error('请上传分类图标！'))
              } else {
                return Promise.resolve()
              }
            }
          },
        ]}>
            <Upload preview={false} imageUrl={icon || form.getFieldValue('icon')} setImageUrl={setIcon} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
